package com.kfyang.manualgear.daoplugin.util;

import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.search.PsiShortNamesCache;
import com.kfyang.manualgear.daoplugin.Constants;

public class PsiUtils {
    public static boolean inManualGear(PsiElement element) {
        PsiFile topLevelFile = InjectedLanguageManager.getInstance(element.getProject()).getTopLevelFile(element);
        String yamlFileName = topLevelFile.getName();
        String className = yamlFileName.substring(0, yamlFileName.lastIndexOf('.'));

        PsiFile[] classFiles = PsiShortNamesCache.getInstance(element.getProject())
            .getFilesByName(className + ".java");
        return classFiles.length == 1;
    }

    public static boolean isDaoMethod(PsiElement element) {
        if (!(element instanceof PsiMethod psiMethod)) {
            return false;
        }
        PsiElement parent = psiMethod.getParent();
        return parent instanceof PsiClass psiClass && psiClass.isInterface() &&
            psiClass.getAnnotation(Constants.DAO_ANNO) != null;
    }

    public static PsiElement findParent(PsiElement element, int deep) {
        PsiElement parent = element;
        for (int i = 0; i < deep; i++) {
            if (parent.getParent() == null) {
                return null;
            }
            parent = parent.getParent();
        }
        return parent;
    }
}
